<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
     <!-- 全选区域 -->
      <label class="radio" @click="changeAllCheckState">
        <radio color="#C00000" :checked="isAllCheck" /><text>全选</text>
      </label>

      <!-- 合计区域 -->
      <view class="amount-box">
        合计:<text class="amount">￥{{checkedGoodsPrice}}</text>
      </view>
      
      <!-- 结算区域 -->
      <view class="btn-settle" @click="settleClickHandler">结算({{checkedGoodsAmount}})</view>
  </view>
</template>

<script>
  
  import { mapGetters, mapState, mapMutations } from 'vuex'
  
  export default {
    name:"my-settle",
    data() {
      return {
        second: 3
      };
    },
    computed:{
      ...mapGetters('m_cart', ['isAllCheck', 'checkedGoodsPrice', 'checkedGoodsAmount']),
      ...mapGetters('m_user', ['addstr']),
      ...mapState('m_user', ['token']),
      ...mapState('m_cart', ['cart']),
    },
    methods: {
      ...mapMutations('m_cart', ['updateGoodsAllCheckState']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      changeAllCheckState(e){
        console.log(this.isAllCheck)
        this.updateGoodsAllCheckState(!this.isAllCheck)
      },
      // 结算事件处理函数
      settleClickHandler(e){
        // 1 收获地址 
        if(!this.addstr) return uni.$showMsg('请选择收获地址')
        // 2 至少选中一件商品
        if(this.checkedGoodsAmount===0) return uni.$showMsg('请至少选中一件商品')
        // 3 用户登录
        if(!this.token) return this.dealyNavigate()
        
        // 4 准备支付
        this.payOrder()
        
      },
      // 延迟跳转
      dealyNavigate(){
        // 控制台倒计数 
        for(let i = 0; i<=this.second; i ++){
          setTimeout(()=> {
            if(i === 3){
              // console.log('tiaozhuan')
              uni.switchTab({
                url: '/pages/my/my',
                success: () => {
                  console.log('切换成功')
                  // 保存到了vuex中
                  this.updateRedirectInfo({
                    // 跳转的方式
                    openType: 'switchTab',
                    // 从哪个页面跳转过去的
                    from: '/pages/cart/cart',
                  })
                }
              })
            }else{
              uni.showToast({
                duration: 1000,
                title: `未登录，将在${this.second-i}秒后跳转到登录页面`,
                mask: true,
                icon: 'none'
              })
            }
          }, i*1000)
        }
      },
      
      // 准备支付
      async payOrder(){
        // 1 生成订单
        console.log('====>>>>')
        // 准备订单参数
        const data = {
          // order_price: this.checkedGoodsPrice,
          order_price: 0.01,
          consignee_addr: this.addstr,
          goods: this.cart.filter(item => item.goods_state)
                          .map(item => ({
                            goods_id: item.goods_id,
                            goods_number: item.goods_count,
                            goods_price: item.goods_price
                          }))
        }
        
        // 发起请求
        console.log(data)
        const {data: res} = await uni.$http.post('/my/orders/create', data)
        // 异常数据判断
        if(res.meta.status !== 200 ) return uni.$showMsg('订单创建失败')
        // 订单编号
        const order_number = res.message.order_number
        
        console.log('==>>',order_number)
        
        // 2 获取支付参数
        const { data: res2 } = await uni.$http.post('/my/orders/req_unifiedorder', {order_number})
        // 异常数据判断
        if(res2.meta.status !== 200) return uni.$showMsg('获取支付参数失败')
        // 微信支付参数
        const payInfo = res2.message.pay
        console.log('zhifu==>',payInfo)
        
        // 3 发起微信支付
        const [err, succ] = await uni.requestPayment(payInfo)
        console.log('==>支付结果', err, succ)
        // 异常数据判断
        if(err) return uni.$showMsg('微信支付失败')
        
        // 4 确认钱有没有到账（公司）
        const { data: res3 } = await uni.$http.post('/my/orders/chkOrder', { order_number: order_number })
        // 数据异常判断
        if(res3.meta.status !== 200) return uni.$showMsg('订单未支付！')
        
        // 钱到账了，支付成功
         uni.showToast({
           title: '支付完成！',
           icon: 'success'
         })
        
      }
      
      
    }
  }
</script>

<style lang="scss">
.my-settle-container {
  /* 底部固定定位 */
  position: fixed;
  bottom: 0;
  left: 0;
  /* 设置宽高和背景色 */
  width: 100%;
  z-index: 9;
  height: 50px;
  background-color: #ffffff;
  
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 5px;
    font-size: 14px;
  
    .radio {
      display: flex;
      align-items: center;
    }
  
    .amount-box {
      .amount {
        color: #c00000;
      }
    }
  
    .btn-settle {
      height: 50px;
      min-width: 100px;
      background-color: #c00000;
      color: white;
      line-height: 50px;
      text-align: center;
      padding: 0 10px;
    }
}
</style>
